package com.jc.business.order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jc.service.yzpService.YZPOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jc.business.base.BaseBusiness;
import com.jc.cds.model.CustomXorder;
import com.jc.common.util.Base64Util;
import com.jc.common.util.ExceptionUtil;
import com.jc.common.util.HttpUtil;
import com.jc.common.util.MD5;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.OrderProducts;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderProcess;
import com.jc.framework.enums.Booleans;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.JgApi;
import com.jc.framework.enums.LogType;
import com.jc.framework.enums.OrderStatus;
import com.jc.framework.enums.SystemUser;
import com.jc.service.api.yx163.order.YanXuanOrderService;
import com.jc.service.jgservice.JgHttpService;
import com.jc.service.model.jg.RequestAddOrder;
import com.jc.service.model.jg.RequestBaseModel;
import com.jc.service.order.XorderService;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.systemloglist.SystemLogListService;
import com.jc.service.xorderprocess.XorderProcessService;
import com.jc.service.zflservice.ZflOrderService;

@Service
public class PushOrderBusiness extends BaseBusiness {
	
	@Autowired
	SystemLogListService systemLogListService;
	@Autowired
	XorderService xorderService;
	@Autowired
	YanXuanOrderService yanXuanOrderService;
	@Autowired
	private ZflOrderService zflOrderService;
	
	@Autowired
	OrderProductsService orderProductsService;
	@Autowired
	JgHttpService jgHttpService;
	@Autowired
	private YZPOrderService yzpOrderService;
	
	@Autowired
	XorderProcessService xorderProcessService;
	
	@Value("${jg.secret}")
	private String appSecret;
	@Value("${jg.appkey}")
	private String appKey;
	@Value("${jg.url}")
	private String url;
	@Value("${jg.order.express.callbackurl}")
	private String callbackurl;
	
	@Transactional
	public boolean pushOrderToJG(RequestAddOrder order) {
		String result = "";	
		String requestUrl = url + JgApi.PUSH_ORDER_URL.getName();
		String dataJson = JSONObject.toJSONString(order);
		String data = Base64Util.encode(dataJson);
		String sign = MD5.passmd5(data + appSecret).toUpperCase();
		RequestBaseModel requestBaseModel = new RequestBaseModel();
		requestBaseModel.setAppKey(appKey);
		requestBaseModel.setData(data);
		requestBaseModel.setSign(sign);
		String body = JSON.toJSONString(requestBaseModel);
		try {
			result = HttpUtil.postJson(requestUrl, body, null);
			JSONObject returnObject = JSONObject.parseObject(result);
			if(StringUtils.isBlank(order.getOrderId())) {
				throw new BaseServiceException("推送错误，orderId为空!");
			}
			Xorder _order = xorderService.queryById(Long.valueOf(order.getOrderId()));
			
			if(returnObject != null && returnObject.getInteger("code") == 10000) {
				JSONObject returnDataObject = returnObject.getJSONObject("data");
				if(returnDataObject == null || StringUtils.isBlank(returnDataObject.getString("result"))) {
					Xorder xorder = new Xorder();
					xorder.setId(Long.valueOf(order.getOrderId()));
					xorder.setOrderStatus(OrderStatus.push_final.getName());
					xorderService.modify(xorder, false);
					systemLogListService.addSystemLog(body, Conclusion.FAIL, null, LogType.PUSH_JG_ORDER, result);
					
					
					if(_order != null) {
						xorderProcessService.addXorderProcess(_order.getChannelOrderId(), "向吉贡推送订单失败,失败原因: 吉贡返回值中 data 节点为空, 或者 data节点为空 "  , SystemUser.ADMIN.getName(), _order.getId());
					}
					return false;
				}
				String supplierOrderSn = returnDataObject.getString("result");
				//
				Map<String,Object> _paramMap = new HashMap<String,Object>();
				_paramMap.put("orderSn", supplierOrderSn);
				_paramMap.put("paymentFee", "1");
				_paramMap.put("payType", "99");
				_paramMap.put("payId", "0");
				_paramMap.put("notifyUrl", callbackurl);
				jgHttpService.httpJgUtil(JgApi.CONFIRM_ORDER_URL.getName(),_paramMap, LogType.PUSH_JG_CONFIRM_ORDER);
				//
				JSONArray detailArray = returnDataObject.getJSONArray("orderDetailList");
				String supperChildOrderId = null ;
				OrderProducts _query = new OrderProducts();
				_query.setOrderId(Long.valueOf(order.getOrderId()));
				_query.setIsDelete(Booleans.FALSE.getName());
				_query.setIsBind(0);
				_query.setIsGift(Booleans.FALSE.getName());
				_query.setSubGoods(1);
				List<OrderProducts> _orderProductList = orderProductsService.queryAll(_query);
				for(int i = 0 ; detailArray != null && i < detailArray.size() ; i++) {
					JSONObject supplierProductObject = detailArray.getJSONObject(i);
					String supplier_sku_id = supplierProductObject.getString("productId");
					String supplier_return_id = supplierProductObject.getString("id");
					String supplier_child_order_id = supplierProductObject.getString("apiOrderSn");
					for(OrderProducts op : _orderProductList) {
						String productId = op.getSupplierProductId();
						if(StringUtils.equals(productId , supplier_sku_id)) {
							op.setSupplierChildOrderId(supplier_child_order_id);
							op.setSupplierReturnId(supplier_return_id);
							orderProductsService.modify(op, false);
						}
					}
				}
				Xorder xorder = new Xorder();
				if(StringUtils.isNotBlank(supperChildOrderId)) xorder.setSupplierOrderNo(supperChildOrderId);
				xorder.setId(Long.valueOf(order.getOrderId()));
				xorder.setOrderStatus(OrderStatus.push_ok.getName());
				xorderService.modify(xorder, false);
				systemLogListService.addSystemLog(body, Conclusion.OK, null, LogType.PUSH_JG_ORDER, result);
				if(_order != null) {
					xorderProcessService.addXorderProcess(_order.getChannelOrderId(), "向吉贡推送订单成功 "  , SystemUser.ADMIN.getName(), _order.getId());
				}
			}else {
				Xorder xorder = new Xorder();
				xorder.setId(Long.valueOf(order.getOrderId()));
				xorder.setOrderStatus(OrderStatus.push_final.getName());
				xorderService.modify(xorder, false);
				
				
				if(_order != null) {
					String errorMessage = returnObject.getString("message") == null ? "" : returnObject.getString("message");
					xorderProcessService.addXorderProcess(_order.getChannelOrderId(), "向吉贡推送订单失败,失败原因: " + errorMessage, SystemUser.ADMIN.getName(), _order.getId());
				}
				
				
				systemLogListService.addSystemLog(body, Conclusion.FAIL, null, LogType.PUSH_JG_ORDER, result);
			}
		}catch (Exception e) {
			Xorder xorder = new Xorder();
			xorder.setId(Long.valueOf(order.getOrderId()));
			xorder.setOrderStatus(OrderStatus.push_final.getName());
			xorderService.modify(xorder, false);
			systemLogListService.addSystemLog(body, Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 150), LogType.PUSH_JG_ORDER, result);
		}
		
		return false;
	}
	
	
	public void confirmOrder() {
		
		
		
	}
	
	
	public boolean pushOrderToZFL(CustomXorder order) {
		zflOrderService.orderPush(order);
		return false;
	}

	public boolean pushOrderToYZP(CustomXorder order) {
		yzpOrderService.xOrder(order);
		return false;
	}
	
	
	
	public boolean pushOrderToYanXuan(CustomXorder order) {
		yanXuanOrderService.pushOrder(order);
		return false;
	}
	
	
//	public void pushLogisticsToH5(String channelOrderId,String ) {
//		
//		
//		
//		
//		
//		
//		
//		
//	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
